local oo = require("SharedLibs.BaseLib")
local co = require("SharedLibs.CoroLib")

Debugger = require("SharedLibs.Debugger")

ISignal = require("SharedLibs.Signal.ISignal")
Signal = require("SharedLibs.Signal.Signal")
WaitSignal = require("SharedLibs.Signal.WaitSignal")

--- SignalWrapper只能传递数据，没有Emit方法直接发射数据
local SignalMerger = oo.class("SignalMerger");
SignalMerger:implements(ISignal);

--- 注册到co里
co.SignalMerger = SignalMerger;

--- dataWrapper接收任意个参数(...)， 返回 (ret, ...)。
--- 返回值：第一个是false，则这个data被过滤掉。否则，将Emit(...)
function SignalMerger:constructor(...)	
	self.name = "";	
	
	self._signal = Signal.new();
	
	self._srcSignals = {};
	
	for i, s in ipairs({...}) do 
		table.insert(self._srcSignals, s);
	end
end

function SignalMerger:On(handler, retDestroyer)
	self._signal:On(handler);
	
	if self._signal:GetHandlerCount() == 1 then
		self._onSrcSignal = function(...)
			self._signal:Emit(...);
		end;
		
		for _, s in ipairs(self._srcSignals) do
			s:On(self._onSrcSignal);	
		end
	end

	if retDestroyer then return function() self:Off(handler); end end	
end

function SignalMerger:Off(handler)
	self._signal:Off(handler);

	if self._signal:GetHandlerCount() == 0 then
		for _, s in ipairs(self._srcSignals) do
			s:Off(self._onSrcSignal);
		end
	end
end

function SignalMerger:Clear()
	if self._signal:GetHandlerCount() == 0 then return end;
 
	self._signal:Clear();
	
	for _, s in ipairs(self._srcSignals) do
		s:Off(self._onSrcSignal);	
	end
end

function SignalMerger:GetHandlerCount()
	return self._signal:GetHandlerCount();
end

function SignalMerger:HasHandler(listener)
	return self._signal:HasHandler(listener);
end

return SignalMerger;
